﻿using System.Collections.Generic;

namespace Sai.Core.Reporting
{
    public class ReportOutputFactory : IReportOutputFactory
	{
		public ReportOutputFactory(string folder, string extension)
		{
			this.Folder = folder;
            this.Extension = extension;
		}

		private string Folder { get; set; }

        private string Extension { get; set; }

        private HashSet<string> allFiles = new HashSet<string>();

		public IReportOutput Create(IProductReleaseDifference difference)
		{
            return CreateUniqueReportOutput(difference.Name);
		}

		public IReportOutput Create(IAssemblyDifference difference)
		{
            return CreateUniqueReportOutput(difference.Name);
        }

		public IReportOutput Create(ITypeDifference difference)
		{
            return CreateUniqueReportOutput(difference.FullName.ToSafeFileName());
        }

        public IReportOutput Create(ITypeListing listing)
        {
            return CreateUniqueReportOutput(listing.Name);
        }

        private IReportOutput CreateUniqueReportOutput(string name)
        {
            string filePath = CreateFullPath(name);

            int copyIndex = 1;
            while(allFiles.Contains(filePath))
            {
                filePath = CreateFullPath(name, copyIndex);
                ++copyIndex;
            }

            allFiles.Add(filePath);

            return new FileReportOutput(filePath);
        }

        private string CreateFullPath(string partialName, int index = 0)
        {
            if (index > 0)
            {
                return System.IO.Path.Combine(this.Folder, string.Format("{0}{1}{2}", partialName, index, this.Extension));
            }

            return System.IO.Path.Combine(this.Folder, string.Format("{0}{1}", partialName, this.Extension));
        }

	}
}
